/**
 * 数据可视化增强模块 - 基于配色规范的图表组件
 */

class DataVisualization {
    constructor() {
        this.colors = {
            primary: '#1e3a8a', secondary: '#64748b', success: '#059669',
            warning: '#d97706', danger: '#dc2626', info: '#0284c7',
            status: {
                'idle': '#64748b', 'in_use': '#059669', 'borrowed': '#0284c7',
                'maintenance': '#d97706', 'faulty': '#dc2626', 'scrapped': '#6b7280'
            }
        };
        this.init();
    }

    init() {
        console.log('📊 初始化数据可视化模块...');
        setTimeout(() => {
            this.createAssetStatusChart();
            this.createDepartmentChart();
            this.createTrendChart();
        }, 1000);
    }

    createAssetStatusChart() {
        const container = this.createChartContainer('asset-status-viz', '资产状态分布');
        if (!container) return;

        const data = [
            { status: 'in_use', label: '在用', count: 156, percentage: 65 },
            { status: 'idle', label: '闲置', count: 45, percentage: 19 },
            { status: 'borrowed', label: '已借出', count: 23, percentage: 10 },
            { status: 'maintenance', label: '维修中', count: 8, percentage: 3 },
            { status: 'faulty', label: '故障', count: 5, percentage: 2 },
            { status: 'scrapped', label: '已报废', count: 3, percentage: 1 }
        ];

        const chart = this.createDonutChart(data);
        container.appendChild(chart);
    }

    createDepartmentChart() {
        const container = this.createChartContainer('dept-chart-viz', '部门资产分布');
        if (!container) return;

        const data = [
            { dept: 'IT部门', count: 89, value: 2450000, color: this.colors.primary },
            { dept: '财务部', count: 34, value: 890000, color: this.colors.success },
            { dept: '行政部', count: 28, value: 560000, color: this.colors.warning },
            { dept: '销售部', count: 45, value: 1230000, color: this.colors.info }
        ];

        const chart = this.createBarChart(data);
        container.appendChild(chart);
    }

    createTrendChart() {
        const container = this.createChartContainer('trend-chart-viz', '资产价值趋势');
        if (!container) return;

        const canvas = document.createElement('canvas');
        canvas.width = 300;
        canvas.height = 150;
        canvas.style.cssText = 'width: 100%; height: 150px; margin: 10px 0;';
        
        const ctx = canvas.getContext('2d');
        this.drawTrendLine(ctx, canvas.width, canvas.height);
        container.appendChild(canvas);
    }

    createChartContainer(id, title) {
        const statsGrid = document.querySelector('.stats-grid');
        if (!statsGrid) return null;

        const container = document.createElement('div');
        container.id = id;
        container.className = 'stats-card';
        container.innerHTML = `
            <h3><i class="fas fa-chart-pie"></i> ${title}</h3>
            <div class="chart-content"></div>
        `;
        statsGrid.appendChild(container);
        return container.querySelector('.chart-content');
    }

    createDonutChart(data) {
        const container = document.createElement('div');
        container.style.cssText = 'display: flex; align-items: center; gap: 15px;';

        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('width', '120');
        svg.setAttribute('height', '120');
        
        const total = data.reduce((sum, item) => sum + item.count, 0);
        let currentAngle = 0;
        const radius = 50;
        const centerX = 60;
        const centerY = 60;

        data.forEach((item, index) => {
            const percentage = item.count / total;
            const angle = percentage * 2 * Math.PI;
            
            if (percentage > 0) {
                const x1 = centerX + radius * Math.cos(currentAngle);
                const y1 = centerY + radius * Math.sin(currentAngle);
                const x2 = centerX + radius * Math.cos(currentAngle + angle);
                const y2 = centerY + radius * Math.sin(currentAngle + angle);
                
                const largeArc = angle > Math.PI ? 1 : 0;
                const pathData = `M ${centerX} ${centerY} L ${x1} ${y1} A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2} Z`;
                
                const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                path.setAttribute('d', pathData);
                path.setAttribute('fill', this.colors.status[item.status]);
                path.setAttribute('stroke', '#ffffff');
                path.setAttribute('stroke-width', '2');
                path.style.cursor = 'pointer';
                
                svg.appendChild(path);
                currentAngle += angle;
            }
        });

        // 中心文本
        const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        text.setAttribute('x', centerX);
        text.setAttribute('y', centerY);
        text.setAttribute('text-anchor', 'middle');
        text.setAttribute('dominant-baseline', 'middle');
        text.style.cssText = `font-size: 16px; font-weight: bold; fill: ${this.colors.primary};`;
        text.textContent = total;
        svg.appendChild(text);

        // 图例
        const legend = document.createElement('div');
        legend.style.cssText = 'flex: 1; display: flex; flex-direction: column; gap: 5px;';
        
        data.forEach(item => {
            const legendItem = document.createElement('div');
            legendItem.style.cssText = 'display: flex; align-items: center; gap: 8px; font-size: 0.8rem;';
            legendItem.innerHTML = `
                <div style="width: 10px; height: 10px; background: ${this.colors.status[item.status]}; border-radius: 2px;"></div>
                <span style="flex: 1; color: #374151;">${item.label}</span>
                <strong style="color: ${this.colors.primary};">${item.count}</strong>
            `;
            legend.appendChild(legendItem);
        });

        container.appendChild(svg);
        container.appendChild(legend);
        return container;
    }

    createBarChart(data) {
        const container = document.createElement('div');
        container.style.cssText = 'display: flex; flex-direction: column; gap: 8px; margin: 10px 0;';

        const maxValue = Math.max(...data.map(item => item.count));

        data.forEach(item => {
            const barContainer = document.createElement('div');
            barContainer.style.cssText = 'display: flex; align-items: center; gap: 8px;';

            const label = document.createElement('div');
            label.style.cssText = 'width: 60px; font-size: 0.75rem; color: #374151; text-align: right;';
            label.textContent = item.dept;

            const track = document.createElement('div');
            track.style.cssText = 'flex: 1; height: 16px; background: #f3f4f6; border-radius: 8px; overflow: hidden;';

            const fill = document.createElement('div');
            const percentage = (item.count / maxValue) * 100;
            fill.style.cssText = `
                height: 100%; background: ${item.color}; width: 0%; 
                transition: width 1s ease; border-radius: 8px;
            `;

            const value = document.createElement('div');
            value.style.cssText = `width: 50px; font-size: 0.75rem; font-weight: 600; color: ${this.colors.primary};`;
            value.textContent = item.count;

            track.appendChild(fill);
            barContainer.appendChild(label);
            barContainer.appendChild(track);
            barContainer.appendChild(value);
            container.appendChild(barContainer);

            setTimeout(() => fill.style.width = `${percentage}%`, 300);
        });

        return container;
    }

    drawTrendLine(ctx, width, height) {
        const padding = 30;
        const chartWidth = width - padding * 2;
        const chartHeight = height - padding * 2;

        ctx.clearRect(0, 0, width, height);

        // 网格
        ctx.strokeStyle = '#e5e7eb';
        ctx.lineWidth = 1;
        for (let i = 0; i <= 5; i++) {
            const y = padding + (chartHeight / 5) * i;
            ctx.beginPath();
            ctx.moveTo(padding, y);
            ctx.lineTo(width - padding, y);
            ctx.stroke();
        }

        // 趋势线数据
        const data = [8500, 8720, 8950, 9200, 9450, 9680, 9890, 10100, 10350, 10580, 10820, 11000];
        const min = Math.min(...data);
        const max = Math.max(...data);
        const range = max - min;

        ctx.strokeStyle = this.colors.primary;
        ctx.lineWidth = 3;
        ctx.beginPath();

        data.forEach((value, i) => {
            const x = padding + (chartWidth / (data.length - 1)) * i;
            const y = height - padding - ((value - min) / range) * chartHeight;
            
            if (i === 0) ctx.moveTo(x, y);
            else ctx.lineTo(x, y);
        });

        ctx.stroke();

        // 数据点
        ctx.fillStyle = this.colors.primary;
        data.forEach((value, i) => {
            const x = padding + (chartWidth / (data.length - 1)) * i;
            const y = height - padding - ((value - min) / range) * chartHeight;
            ctx.beginPath();
            ctx.arc(x, y, 3, 0, 2 * Math.PI);
            ctx.fill();
        });
    }

    refreshChart(chartId) {
        console.log(`🔄 刷新图表: ${chartId}`);
        window.advancedFeatures?.showNotification('图表刷新', '数据已更新到最新状态', 'success');
    }

    exportChart(chartId) {
        console.log(`📥 导出图表: ${chartId}`);
        window.advancedFeatures?.showNotification('图表导出', '图表已导出为PNG文件', 'success');
    }
}

// 自动初始化
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        window.dataVisualization = new DataVisualization();
        console.log('✅ 数据可视化模块已启动');
    }, 2000);
});